const importLazy = require('import-lazy')(require);
const inquirer = require('inquirer');

const Okapi = importLazy('../okapi/okapiRepository.js');
const AuthService = importLazy('../okapi/authService.js');

module.exports = async function login() {
  const answers = await inquirer.prompt([
    {
      type: 'input',
      name: 'username',
      message: '请输入您的用户名',
    },
    {
      type: 'password',
      name: 'password',
      mask: true,
      message: '请输入您的密码',
    },
    {
      type: 'input',
      name: 'okapiUrl',
      message: '请输入okapiUrl地址',
    },
    {
      type: 'input',
      name: 'tenant',
      message: '请输入租客类型',
    },
  ]);
  const { okapiUrl, tenant, username, password } = answers;

  const okapi = new Okapi(okapiUrl, tenant);
  const authService = new AuthService(okapi);

  return authService
    .login(username, password)
    .then(() => {
      console.log(`User ${username} logged into tenant ${tenant} on Okapi ${okapiUrl}`);
    })
    .catch((err) => {
      console.log('Error logging in.', err);
    });
};
